'use client';

import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import {
  createContact,
  removeContact,
  updateUserPersonalityInfo,
} from '@/services/api';
import type { TBody } from '@/types';
import type {
  IContact,
  ICreateContactBody,
  IDifference,
  IRemoveContactBody,
  IUpdateUserPersonalityInfoBody,
  IUser,
} from '@/interfaces';
import diff from 'microdiff';
import useToast from '@/hooks/useToast';
import { getDiffData, getFilterData, isEmpty } from '@/lib/tool';

export default function UpdateUserPersonality(
  this: any,
  { details }: { details: IUser },
) {
  const [form, setForm] = useState<{
    personalizedSignature?: string;
    smallAvatarUrl?: string;
    mediumAvatarUrl?: string;
    largeAvatarUrl?: string;
    contacts?: {
      id: string;
      key: string;
      val: string;
    }[];
    about?: string;
  }>({
    personalizedSignature: '',
    smallAvatarUrl: '',
    mediumAvatarUrl: '',
    largeAvatarUrl: '',
    contacts: [],
    about: '',
  });
  const [contact, setContact] = useState<{
    key: string;
    val: string;
  }>({
    key: '',
    val: '',
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const { show } = useToast();
  const queryClient = useQueryClient();

  const updateUserPersonalityInfoMutation = useMutation(
    async (variables: TBody<IUpdateUserPersonalityInfoBody>) => {
      await updateUserPersonalityInfo(variables);
    },
  );
  const createContactMutation = useMutation(
    async (variables: TBody<ICreateContactBody>) => {
      await createContact(variables);
      await queryClient.refetchQueries(['/users', details.id]);
    },
  );
  const removeContactMutation = useMutation(
    async (variables: TBody<IRemoveContactBody>) => {
      await removeContact(variables);
      await queryClient.refetchQueries(['/users', details.id]);
    },
  );

  useEffect(() => {
    if (details) {
      const userDetails = details.details!;
      setForm({
        personalizedSignature: userDetails.personalizedSignature || '',
        smallAvatarUrl: userDetails.smallAvatarUrl || '',
        mediumAvatarUrl: userDetails.mediumAvatarUrl || '',
        largeAvatarUrl: userDetails.largeAvatarUrl || '',
        contacts: userDetails.contacts || [],
        about: userDetails.about || '',
      });
    }
  }, [details]);
  useEffect(() => {
    if (details) {
      const userDetails = details.details!;
      const differences = diff(
        {
          personalizedSignature: userDetails.personalizedSignature || '',
          smallAvatarUrl: userDetails.smallAvatarUrl || '',
          mediumAvatarUrl: userDetails.mediumAvatarUrl || '',
          largeAvatarUrl: userDetails.largeAvatarUrl || '',
          contacts: userDetails.contacts || [],
          about: userDetails.about || '',
        },
        form,
      );
      setDifferenceData(differences);
    }
  }, [form, details]);

  function onChangeForm(
    e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
  ) {
    const name = e.target.name;
    const value = e.target.value;
    setForm({ ...form, [name]: value });
  }

  function onChangeContact(e: ChangeEvent<HTMLInputElement>) {
    const name = e.target.name;
    const value = e.target.value.trim();

    if (name === 'contact-name') {
      setContact({ ...contact, key: value });
    } else if (name === 'contact-content') {
      setContact({ ...contact, val: value });
    }
  }

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const body = getFilterData(getDiffData(differenceData));
      if (isEmpty(body)) {
        show({
          type: 'SUCCESS',
          message: '保存完成',
        });
        return;
      }

      await updateUserPersonalityInfoMutation.mutateAsync({
        id: details.id,
        data: body,
      });

      clearData();
      show({
        type: 'SUCCESS',
        message: '保存完成',
      });
    } catch (e) {
      updateUserPersonalityInfoMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  async function onClickCreateContact() {
    try {
      if (!contact.key || !contact.val) {
        show({
          type: 'DANGER',
          message: '请输入联系方式',
        });
        return;
      }

      await createContactMutation.mutateAsync({
        id: details.id,
        data: contact,
      });

      show({
        type: 'SUCCESS',
        message: '添加完成',
      });
    } catch (e) {
      createContactMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  async function onClickRemoveContact(item: IContact) {
    try {
      await removeContactMutation.mutateAsync({
        id: details.id,
        data: {
          contactId: item.id,
        },
      });

      show({
        type: 'SUCCESS',
        message: '删除完成',
      });
    } catch (e) {
      removeContactMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function clearData() {
    setDifferenceData([]);
  }

  return (
    <div className="row">
      <div className="col">
        <form onSubmit={onClickSave} className="vstack gap-4">
          <div>
            <label className="form-label">个性签名</label>
            <input
              type="text"
              className="form-control"
              name="personalizedSignature"
              value={form.personalizedSignature}
              onChange={onChangeForm}
              aria-describedby="personalizedSignature"
              placeholder="请输入个性签名"
            />
          </div>

          <div>
            <label className="form-label">小的头像</label>
            <input
              type="text"
              className="form-control"
              name="smallAvatarUrl"
              value={form.smallAvatarUrl}
              onChange={onChangeForm}
              aria-describedby="smallAvatarUrl"
              placeholder="请输入小的头像地址"
            />
          </div>

          <div>
            <label className="form-label">中等头像</label>
            <input
              type="text"
              className="form-control"
              name="mediumAvatarUrl"
              value={form.mediumAvatarUrl}
              onChange={onChangeForm}
              aria-describedby="mediumAvatarUrl"
              placeholder="请输入中等头像地址"
            />
          </div>

          <div>
            <label className="form-label">大的头像</label>
            <input
              type="text"
              className="form-control"
              name="largeAvatarUrl"
              value={form.largeAvatarUrl}
              onChange={onChangeForm}
              aria-describedby="largeAvatarUrl"
              placeholder="请输入大的头像地址"
            />
          </div>

          <div>
            <label className="form-label">联系方式</label>

            <div>
              <div className="table-responsive">
                <table className="table table-hover align-middle">
                  <thead>
                    <tr className="text-nowrap">
                      <th scope="col" className="w-10 fw-normal">
                        名称
                      </th>
                      <th scope="col" className="w-10 fw-normal">
                        内容
                      </th>
                      <th scope="col" className="w-10"></th>
                    </tr>
                  </thead>
                  <tbody>
                    {(details.details!.contacts || []).map((item) => {
                      return (
                        <tr key={item.id} className="text-nowrap">
                          <td>{item.key}</td>
                          <td>{item.val}</td>
                          <td>
                            <button
                              disabled={removeContactMutation.isLoading}
                              onClick={onClickRemoveContact.bind(this, item)}
                              className="btn btn-sm btn-danger"
                              type="button"
                            >
                              {removeContactMutation.isLoading ? (
                                <span
                                  className="spinner-border spinner-border-sm me-2"
                                  role="status"
                                  aria-hidden="true"
                                ></span>
                              ) : (
                                <i className="bi bi-trash me-2"></i>
                              )}
                              删除
                            </button>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>

              {(form.contacts || []).length === 0 && (
                <div className="text-muted">暂无联系方式</div>
              )}
            </div>

            <div className="input-group mt-4">
              <input
                type="text"
                className="form-control"
                placeholder="请输入名称"
                value={contact.key}
                name="contact-name"
                aria-label="contact-name"
                onChange={onChangeContact}
              />
              <input
                type="text"
                className="form-control"
                placeholder="请输入内容"
                value={contact.val}
                name="contact-content"
                aria-label="contact-content"
                onChange={onChangeContact}
              />
              <button
                disabled={createContactMutation.isLoading}
                onClick={onClickCreateContact}
                className="btn btn-outline-primary"
                type="button"
              >
                {createContactMutation.isLoading ? (
                  <span
                    className="spinner-border spinner-border-sm me-2"
                    role="status"
                    aria-hidden="true"
                  ></span>
                ) : (
                  <i className="bi bi-plus-lg me-2"></i>
                )}
                添加
              </button>
            </div>
          </div>

          <div>
            <label className="form-label">关于我</label>
            <textarea
              rows={3}
              className="form-control"
              name="about"
              value={form.about}
              onChange={onChangeForm}
              aria-describedby="about"
              placeholder="请输入关于我"
            />
          </div>

          <button
            type="submit"
            disabled={updateUserPersonalityInfoMutation.isLoading}
            className="btn btn-success w-25 my-4"
          >
            {updateUserPersonalityInfoMutation.isLoading && (
              <span
                className="spinner-border spinner-border-sm me-2"
                role="status"
                aria-hidden="true"
              ></span>
            )}
            更新
          </button>
        </form>
      </div>
    </div>
  );
}
